<template>
  <view>
    <wd-form ref="form" :rules="props.rules">
      <wd-cell-group
        custom-class="group"
        :title="category || ''"
        border
        v-for="([category, items], catIndex) in Object.entries(schemaList)"
        :key="catIndex"
      >
        <view v-for="(item, index) in items" :key="`${catIndex}-${index}`">
          <wd-input
            v-if="item.type === 'Input'"
            :label="item.label"
            label-width="100px"
            show-word-limit
            :prop="item.field"
            suffix-icon="warn-bold"
            clearable
            v-model="formData[item.field]"
            :placeholder="`请输入${item.label}`"
          />
          <wd-input
            v-if="item.type === 'InputAddress'"
            :label="item.label"
            label-width="100px"
            show-word-limit
            :prop="item.field"
            suffix-icon="location"
            v-model="formData[item.field]"
            :placeholder="`请输入${item.label}`"
            @click="selectAddress(item)"
          />
          <wd-input
            v-if="item.type === 'Password'"
            :label="item.label"
            label-width="100px"
            show-word-limit
            :prop="item.field"
            suffix-icon="warn-bold"
            type="password"
            clearable
            v-model="formData[item.field]"
            :placeholder="`请输入${item.label}`"
          />
          <wd-cell
            :title="item.label"
            title-width="100px"
            v-if="item.type === 'Number'"
          >
            <view style="text-align: left">
              <wd-input-number v-model="formData[item.field]" />
            </view>
          </wd-cell>
          <wd-cell
            :title="item.label"
            title-width="100px"
            v-if="item.type === 'Calendar'"
          >
            <wd-calendar
              v-model="formData[item.field]"
              :placeholder="`请选择${item.label}`"
            />
          </wd-cell>
          <wd-cell
            :title="item.label"
            title-width="100px"
            v-if="item.type === 'Select'"
          >
            <wd-picker
              :columns="item?.options?.map((item) => item.name) || []"
              v-model="formData[item.field]"
              @confirm="calenConfirm"
            />
          </wd-cell>
          <wd-cell
            :title="item.label"
            title-width="100px"
            v-if="item.type === 'Textarea'"
          >
            <wd-textarea
              v-model="formData[item.field]"
              :placeholder="`请输入${item.label}`"
            />
          </wd-cell>
          <wd-cell
            :title="item.label"
            title-width="100px"
            v-if="item.type === 'Upload'"
          >
            <view class="flex gap-2">
              <view v-for="index in [1, 2]" :key="index">
                <view
                  class="bod w-[140rpx] h-[140rpx] flex items-center justify-center"
                  v-if="!fileList[index - 1]"
                  @click="uploadFile(index)"
                >
                  <wd-icon name="add" size="40rpx" color="#999" />
                </view>
                <view
                  class="w-[140rpx] h-[140rpx] flex items-center justify-center"
                  v-else
                >
                  <image
                    class="w-[100%] h-[100%]"
                    :src="fileList[index - 1]"
                    mode="scaleToFill"
                  />
                </view>
              </view>
            </view>
          </wd-cell>
        </view>
      </wd-cell-group>
      <wd-cell title-width="0px">
        <view>
          <wd-button type="primary" @click="submitForm">提交</wd-button>
        </view>
      </wd-cell>
    </wd-form>
  </view>
</template>

<script lang="ts" setup>
import { ref, type PropType, onMounted, watch } from 'vue'
import { groupBy } from '@/utils/others'
import { uploadImage } from '@/utils/upload'

const emit = defineEmits(['register', 'submitForm'])

// 动态接收参数，配合钩子进行数据控制
const props = defineProps({
  rules: {
    type: Object,
    required: true
  },
  formSchema: {
    type: Array as PropType<IFormSchema[]>,
    required: true
  },
  initialData: {
    type: Object,
    default: () => ({})
  }
})

const formData = ref<Record<string, any>>({})

const fileList = ref<string[]>([])

const schemaList = groupBy(props.formSchema, (item) => item.cell as string)

const submitForm = () => {
  formData.value.img = fileList.value
  emit('submitForm', formData.value)
}
const calenConfirm = ({ value }: any) => {
  // formData进行循环，由于是对象，需要判断是否是Select类型
  Object.keys(formData.value).forEach((key) => {
    const item = formData.value[key]
    if (item.type === 'Select') {
      const id = item?.options?.find((opt: any) => opt.name === value)?.id
      formData.value[key] = id || ''
    }
  })
}

const selectAddress = (item: IFormSchema) => {
  uni.chooseLocation({
    success: (res) => {
      formData.value[item.field] = res.address
      formData.value['lat'] = res.latitude
      formData.value['lng'] = res.longitude
    }
  })
}

const uploadFile = async (index: number) => {
  const uploadTask = await uploadImage()
  fileList.value[index - 1] = uploadTask
}

watch(
  () => props.initialData,
  (newVal) => {
    console.log('🚀 ~ watch ~ newVal:', newVal)
    formData.value = { ...formData.value, ...newVal }
  },
  { deep: true }
)

function register() {
  props.formSchema.forEach((item) => {
    formData.value[item.field] = ''
    if (item.optionApi) {
      item.optionApi().then((res) => {
        item.options = res || []
        console.log('item.options', item.options)
      })
    }
  })
  formData.value = { ...props.initialData }
  emit('register', formData.value)
}

defineExpose({ register })

onMounted(() => {
  register()
})
</script>

<style lang="scss" scoped>
.footer {
  padding: 12px;
}
.bod {
  border: 2rpx solid #999;
}
</style>
